//
//  TYHRefreshControl.swift
//  TYHWeibo
//
//  Created by IOS on 15/8/7.
//  Copyright © 2015年 IOS. All rights reserved.
//

import UIKit
///下拉刷新的偏移量,超出之后,翻转动画
private let kRefreshPullOffset: CGFloat = -60

class TYHRefreshControl: UIRefreshControl {
    
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopLoading()
    }
    
    // MARK: KVO
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(frame)
        if frame.origin.y > 0 {
            return
        }
        
        //判断是否开始刷新,开始刷新进入动画
        if refreshing {
            refreshView.startLoading()
        }
        
       
        
        if frame.origin.y < kRefreshPullOffset && !refreshView.rotateFlag {
//            print("翻过来")
            refreshView.rotateFlag = true
        } else if frame.origin.y > kRefreshPullOffset && refreshView.rotateFlag {
//            print("转过来")
            refreshView.rotateFlag = false
        }
    }
    
    //构造函数
    override init() {
        super.init()
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    private func setupUI() {
        //kvo监听frame 的变化
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
        //添加控件
        addSubview(refreshView)
        
        //隐藏默认的转轮
        tintColor = UIColor.clearColor()
        
        //布局
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
        
    }
    
    ///懒加载
    private lazy var refreshView: TYHRefreshView = TYHRefreshView.refreshView()

}

class TYHRefreshView: UIView {
    
    private var rotateFlag = false {
        didSet {
            rotateTipIcon()
        }
    }
    @IBOutlet weak var tipIcon: UIImageView!
    @IBOutlet weak var loadingIcon: UIImageView!
    @IBOutlet weak var tipVIew: UIView!
    
    class func refreshView() -> TYHRefreshView {
        return NSBundle.mainBundle().loadNibNamed("TYHRefreshView", owner: nil, options: nil).last as! TYHRefreshView
    }
    
    ///提示图标的翻转
    private func rotateTipIcon() {
        let angle = rotateFlag ? CGFloat (M_PI - 0.01) : CGFloat (M_PI + 0.01)
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, angle)
        }
        
    }
    
    ///开始加载动画
    private func startLoading() {
        
        if (loadingIcon.layer.animationForKey("loadingAnim") != nil) {
            return
        }
        
        //隐藏提示图标
        tipVIew.hidden = true
        
        // 定义动画
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.duration = 1.0
        anim.repeatCount = MAXFLOAT
        anim.toValue = M_PI * 2
        
        loadingIcon.layer.addAnimation(anim, forKey: "loadingAnim")
        
    }
    
    private func stopLoading() {
        tipVIew.hidden = false
        
        loadingIcon.layer.removeAllAnimations()
    }
    
    
}





